package online.shiming.file.util;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;

/**
 * @author ShiMing
 * @version 1.0
 * @name DataDo
 * @description TODO
 * @date 2020/11/13
 */
@Data
@ToString
@Accessors(chain = true)
public class DataDo<T> {

    private static final long serialVersionUID = 1L;

    private List<?> rows = new ArrayList();

    private List<?> footer = new ArrayList();

    private Long total = 0L;

    private String message;

    private T data;

    private int code;

    private boolean isSucceed = true;

    private Map<String, Object> newPrimaryKeys = new HashMap<>();

    public static <T> DataDo<T> error(T data) {
        return restResult(data, SystemStatus.ERROR.getCode(), null, false);
    }

    public static <T> DataDo<T> error() {
        return restResult(null, SystemStatus.ERROR.getCode(), null, false);
    }

    public static <T> DataDo<T> error(String msg) {
        return restResult(null, SystemStatus.ERROR.getCode(), msg, false);
    }

    public static <T> DataDo<T> error(T data, String msg) {
        return restResult(data, SystemStatus.ERROR.getCode(), msg, false);
    }

    public static <T> DataDo<T> ok() {
        return restResult(null, SystemStatus.SUCCESS_CODE.getCode(), null, true);
    }

    public static <T> DataDo<T> ok(T data) {
        return restResult(data, SystemStatus.SUCCESS_CODE.getCode(), null, true);
    }

    public static <T> DataDo<T> ok(T data, String msg) {
        return restResult(data, SystemStatus.SUCCESS_CODE.getCode(), msg, true);
    }

    public static <T> DataDo<T> ok(String msg) {
        return restResult(null, SystemStatus.SUCCESS_CODE.getCode(), msg, true);
    }


    private static <T> DataDo<T> restResult(T data, int code, String msg, boolean isSucceed) {
        DataDo<T> result = new DataDo<>();
        result.setCode(code);
        result.setData(data);
        if (data instanceof List) {
            result.setRows((List) data);
        }
        result.setMessage(msg);
        result.setIsSucceed(isSucceed);
        return result;
    }

    public boolean getIsSucceed() {
        return isSucceed;
    }

    public void setIsSucceed(boolean isSucceed) {
        this.isSucceed = isSucceed;
    }

    public void addNewPrimaryKey(String key, Object value) {
        newPrimaryKeys.put(key, value);
    }

}
